<?php

/**
 * album actions.
 *
 * @package    sfwixet
 * @subpackage album
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class albumActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->forward('default', 'module');
  }
  
  public function executePhotos(sfWebRequest $request){
  	try{
	  	if($albumId=$request->getParameter("id"))
	  	{
	  		$album = Doctrine::getTable("album")->find($request->getParameter("id"));
	  		$photos = $album->getAllowedPhotos($request->getParameter("page",1),$request->getParameter("size",20),$this->getUser());
			echo json_encode(array("album"=>$album->toArray() ,"photos"=>$photos));
	  	}else throw new Exception(_("Please specify an album id"));
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}

    return sfView::NONE;
  }
  public function executeNewName(sfWebRequest $request){
  	if(strlen(trim($request->getParameter("name"))) > 0 && $request->getParameter("id"))
  	{
  		$album = Doctrine::getTable("album")->find($request->getParameter("id"));
  		if($album instanceof Album && $album->getOwnerId()==$this->getUser()->getId())
  		{
  			$album->setName($request->getParameter("name"));
  			$album->save();
  			
  			echo json_encode(array("error"=>false));
  		}else{
  			echo json_encode(array("error"=>true,"message"=>_("You can not view this album")));
  		}
  	}else
  		echo json_encode(array("error"=>true,"message"=>_("Please specify an album name and album id")));

    return sfView::NONE;
  }
  
  public function executeNewPermissions(sfWebRequest $request){
		
  	if(($albumId=$request->getParameter("id")))
  	{
  		$album = Doctrine::getTable("album")->find($request->getParameter("id"));
  		if($album instanceof Album && $album->getOwnerId()==$this->getUser()->getId())
  		{
  			$permissions = json_decode($request->getParameter("permissions"));
  			if($request->isMethod(sfRequest::POST))
  			{
  				//Reset permissions
  				Doctrine::getTable("aclAlbumGroup")->findByAlbumId($albumId)->delete();
	  			foreach($permissions->allowed as $groupId){
	  				
					$group = Doctrine::getTable("aclGroup")->find($groupId->id);
					if($group->getOwnerId() == $this->getUser()->getId())
					{
						$album->grantReadToGroup($group);
						$album->grantWriteToGroup($group);
					}
  				}
  			
				foreach($permissions->denied as $groupId){
	  				
					$group = Doctrine::getTable("aclGroup")->find($groupId->id);
					if($group->getOwnerId() == $this->getUser()->getId())
					{
						$album->denyReadToGroup($group);
						$album->denyWriteToGroup($group);
					}
  				}

  				echo json_encode(array("error"=>false));
  			}else echo json_encode(array("error"=>true,"message"=>_("You should post the allowed and denied groups")));
  		}else{
  			echo json_encode(array("error"=>true,"message"=>_("You can not view this album")));
  		}
  	}else
  		echo json_encode(array("error"=>true,"message"=>_("Please specify an album id")));

    return sfView::NONE;
  }
  
  public function executePermissionsDetails(sfWebRequest $request)
  {
	if($request->getParameter("id"))
  	{
  		$album = Doctrine::getTable("album")->find($request->getParameter("id"));
  		if($album instanceof Album && $album->getOwnerId()==$this->getUser()->getId())
  		{
  			$allowedGroups = array();
  			$deniedGroups = array();
  			$groups = $this->getUser()->getGuardUser()->getMyAclGroups();
  			foreach($groups as $group){
  				$permissions = $album->getPermissionsForGroup($group);
  				if($permissions['read_granted'])
  					$allowedGroups[] = $group->toArray();
  					
  				if($permissions['read_denied'])
  					$deniedGroups[] = $group->toArray();	
  			}
			
  			//This function is used to allow array_udiff to compare groups
  			/*function groupsCompare($group1,$group2)
  			{
  				//if($group1['group_id'] == $group2['group_id'] ? 0:1)
  					echo $group1['group_name']."(".$group1['group_id'].") ==".$group2['group_name']."(".$group2['group_id'].") ".($group1['group_id'] == $group2['group_id'] ? 0:1)."<br>";
  					
  					//echo $group1['group_id'] == $group2['group_id'] ? 0:1;
  				return $group1['group_id'] === $group2['group_id'] ? 0:1;
  			}
			$undefinedAllowedGroups = array_udiff($groups->toArray(),$allowedGroups,"groupsCompare");
			*/
  			
			$undefinedAllowedGroups = $groups->toArray();
			$tam = $groups->count();
			foreach($allowedGroups as $allowedGroup){
				$continue = true;
				 $index = 0;
				while($continue && $index<$tam){
					$continue = $allowedGroup['group_id'] != $undefinedAllowedGroups[$index]['group_id'];
					$index++;
				}
				if(!$continue) unset($undefinedAllowedGroups[$index-1]);
			}

			
			//$undefinedDeniedGroups = array_udiff($groups->toArray(),$deniedGroups,"groupsCompare");
			
  			$undefinedDeniedGroups = $groups->toArray();
			$tam = $groups->count();
			foreach($deniedGroups as $deniedGroup){
				$continue = true;
				 $index = 0;
				while($continue && $index<$tam){
					$continue = $deniedGroup['group_id'] != $undefinedDeniedGroups[$index]['group_id'];
					$index++;
				}
				if(!$continue) unset($undefinedDeniedGroups[$index-1]);
			}
			
  			echo json_encode(array("allowedGroups"=>$allowedGroups,"deniedGroups"=>$deniedGroups,"undefinedAllowedGroups"=>$undefinedAllowedGroups,"undefinedDeniedGroups"=>$undefinedDeniedGroups));
  		}else{
  			echo json_encode(array("error"=>true,"message"=>_("You can not view this album")));
  		}
  	}else
  		echo json_encode(array("error"=>true,"message"=>_("Please specify an album id")));
    return sfView::NONE;
  }
  
  public function executeDetails(sfWebRequest $request)
  {
  	if($request->getParameter("id"))
  	{
  		$album = Doctrine::getTable("album")->find($request->getParameter("id"));
  		if($album instanceof Album && $album->getOwnerId()==$this->getUser()->getId())
  		{
  			$details = $album->toArray();
  			$details['front'] = $album->getFront()->getPhotoId();
  			echo json_encode($details);
  		}else{
  			echo json_encode(array("error"=>true,"message"=>_("You can not view this album")));
  		}
  	}else
  		echo json_encode(array("error"=>true,"message"=>_("Please specify an album id")));
    return sfView::NONE;
  }
  public function executeNew(sfWebRequest $request)
  {
  	if($request->getParameter("name"))
  	{
  		$album = new Album();
  		$album->setOwner($this->getUser());
  		$album->setName($request->getParameter("name"));
  		$album->save();
  		$album->grantAllToGroup($this->getUser()->getGuardUser()->getMainGroup());
  		 echo json_encode(array("error"=>false,"id"=>$album->getAlbumId()));
  	}else
  		echo json_encode(array("error"=>true,"message"=>_("Please write an album name")));
  	return sfView::NONE;
  }
  
  public function executeRemove(sfWebRequest $request)
  {
  	if($request->getParameter("id"))
  	{
  		$album = Doctrine::getTable("album")->find($request->getParameter("id"));
  		if($album instanceof Album && $album->getOwnerId()==$this->getUser()->getId())
  		{
  			if($album->getPhotos()->count()>0)
  				echo json_encode(array("error"=>true,"message"=>_("This album have photos. Please move them before remove the album")));
  			else {
  				try{
  					$album->delete();
  					echo json_encode(array("error"=>false));
  				}catch(Exception $e){
  					echo json_encode(array("error"=>true,"message"=>_("You can not remove your main album")));
  				}
  			}
  		}else{
  			echo json_encode(array("error"=>true,"message"=>_("You can not remove this album")));
  		}	
  		 
  	}else
  		echo json_encode(array("error"=>true,"message"=>_("Please specify an album id")));
  	return sfView::NONE;
  }
  
  
  public function executeGetTaggedAlbum(sfWebRequest $request){
	
  	try{
  		if(is_numeric($request->getParameter("id")))
  			$user = Doctrine::getTable("sfGuardUser")->find($request->getParameter("id"));
  		else
  			$user = $this->getUser();
  			
  	$cnn = Doctrine_Manager::connection();
//This query get the tagged photos allowed by photo permissions
// and next get the tagged photos allowed by album permissions
//Then a sum of permissions and get only allowed by photo and album
// permissions
//$sqlQuery = "SELECT photo_id,sum(read_granted) as read_granted,sum(read_denied) as read_denied,sum(write_granted) as write_granted,sum(write_denied) as write_denied
$page = $request->getParameter("page",1);
if(!is_numeric($page)) $page = 1;
$size = $request->getParameter("size",20);
if(!is_numeric($size)) $size = 20;
$offset = ($page-1)*$size;
$limit = $size;

$sqlQuery = "FROM
((
SELECT photo_id,title,read_granted,read_denied,write_granted,write_denied,owner_id
FROM photo_tag pt
LEFT JOIN photo p USING (photo_id)
LEFT JOIN acl_photo_group pg USING (photo_id)
LEFT JOIN acl_users_groups g1 USING (group_id)
WHERE (pt.user_id = ".$user->getId()." AND g1.user_id = ".$user->getId().") OR p.owner_id = ".$user->getId()."
)
union
(
SELECT photo_id,title,read_granted,read_denied,write_granted,write_denied,owner_id
FROM photo_tag pt
LEFT JOIN photo p USING (photo_id)
LEFT JOIN acl_album_group pg USING (album_id)
LEFT JOIN acl_users_groups g2 USING (group_id)
WHERE (pt.user_id = ".$user->getId()." AND g2.user_id = ".$user->getId().") OR p.owner_id = ".$user->getId()."
)) as permissions
GROUP BY (photo_id)
HAVING ((read_granted > 0 AND read_denied = 0 AND write_granted > 0 AND write_denied = 0) OR owner_id = ".$user->getId().")";
$photoList = $cnn->fetchAssoc("SELECT photo_id,title,read_granted,read_denied,write_granted,write_denied,owner_id "
	.$sqlQuery
	." LIMIT ".$offset.",".$limit);
///Count
$count = $cnn->fetchAssoc("SELECT count(*) as count FROM
							(select photo_id,title,read_granted,read_denied,write_granted,write_denied,owner_id 
						  ".$sqlQuery." ) as num");
$photos = array();
$photos['photos'] = $photoList;
$photos['pagecount'] = ceil($count[0]['count']/$size);
  	/*
  $q = Doctrine_Query::create()
			->from("PhotoTag t")
			->leftJoin("t.photo p")
			->leftJoin("p.aclPhotoGroup pg")
			->leftJoin("pg.aclUsersGroups g1")
			
			->leftJoin("p.album a")
			->leftJoin("a.aclAlbumGroup ag")
			->leftJoin("ag.aclUsersGroups g2")

			->addWhere("IFNULL(pg.read_granted,0) + a4.read_granted > 0")
			->addWhere("IFNULL(pg.write_granted,0) + a4.write_granted > 0")
			->addWhere("IFNULL(pg.read_denied,0) + a4.read_denied = 0")
			->addWhere("IFNULL(pg.write_denied,0) + a4.write_denied = 0")
			
			->addWhere("user_id = ?",$this->getUser()->getId());

echo $q->getSqlQuery();
			$size = 20;
			$page = 1;
			$pager = new sfDoctrinePager('Photo',$size);
			$pager->setQuery($q);
			
	  		$pager->setPage($page);
	  		
	  		$pager->init();
	  		$photos['photos'] = array();
	  		$photos['pagecount'] = $pager->getLastPage();
			foreach($pager->getResults() as $element){
				$photos['photos'][] = $element->photo->toArray(false);
			}*/
			echo json_encode(array("album"=>array("name"=>sfContext::getInstance()->getI18n()->__("Where % is tagged",array("%"=>$user->getFirstname()))) ,"photos"=>$photos));
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true ,"message"=>$e->getMessage()));
  	}
			return sfView::NONE;
  }
}
